<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-row :gutter="24">
        <a-col :span="24 - gutter" v-if="deptFlag">
          <!-- 部门树 -->
            <dept-tree
              ref="deptTree"
              :deptOptions="deptOptions"
              @select="clickDeptNode"
            />
        </a-col>
        <a-col :span="gutter">
          <!-- 条件搜索 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="学员名称" prop="name">
                    <a-input v-model="queryParam.name" placeholder="请输入学员名称" allow-clear/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                    <a-form-item label="手机号" prop="phone">
                      <a-input v-model="queryParam.phone" placeholder="请输入手机号" allow-clear/>
                    </a-form-item>
                  </a-col>
                <template v-if="advanced">
                  <a-col :md="8" :sm="24">
                    <a-form-item label="商机来源" prop="source">
                      <a-select placeholder="请选择商机来源" v-model="queryParam.source" style="width: 100%" allow-clear>
                        <a-select-option v-for="(d, index) in sourceOptions" :key="index" :value="d.dictValue">{{ d.dictLabel }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-item label="商机归属人" prop="ascriptionSale">
                      <a-select placeholder="请选择商机归属人" v-model="queryParam.ascriptionSale" :filterOption="hanleFilter" showSearch>
                        <a-select-option v-for="(d, index) in dataSource" :key="index" :value="d.id" >{{ d.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :md="!advanced && 8 || 24" :sm="24">
                  <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                    <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
                    <a @click="toggleAdvanced" style="margin-left: 8px">
                      {{ advanced ? '收起' : '展开' }}
                      <a-icon :type="advanced ? 'up' : 'down'"/>
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 操作 -->
          <div class="table-operations">
            <a-button type="primary" @click="$refs.createForm.handleAdd(queryParam.deptId);getList()" v-hasPermi="['manager:student:add']">
              <a-icon type="plus" />新增
            </a-button>
            <a-button type="primary" :disabled="multiple" @click="openProxyModel">
              <a-icon type="edit" />代理
            </a-button>
            <a-button type="danger" :disabled="multiple" @click="handleDelete" v-hasPermi="['manager:student:remove']">
              <a-icon type="delete" />删除
            </a-button>
            <a-button type="primary" @click="handleExport" v-hasPermi="['manager:student:export']">
              <a-icon type="download" />导出
            </a-button>
            <table-setting
              :style="{float: 'right'}"
              :table-size.sync="tableSize"
              v-model="columns"
              :refresh-loading="loading"
              @refresh="getList" />
          </div>
          <!-- 增加修改 -->
          <create-form
            ref="createForm"
            :sourceOptions="sourceOptions"
            :intentionOptions="intentionOptions"
            :sexOptions="sexOptions"
            :statusOptions="statusOptions"
            :treeData="deptOptions"
            :classTypeOptions="classTypeOptions"
            @ok="getList"
          />
          <!-- 数据展示 -->
          <a-table 
            :loading="loading"
            :size="tableSize"
            rowKey="id"
            :columns="columns"
            :data-source="list"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :pagination="false"
            :bordered="tableBordered"
          >
            <span slot="name" slot-scope="text,record">
              {{record.name}}
            </span>
            <span slot="birthday" slot-scope="text, record">
              {{ parseTime(record.birthday) }}
            </span>
            <span slot="source" slot-scope="text, record">
              {{ sourceFormat(record) }}
            </span>
            <span slot="intention" slot-scope="text, record">
              {{ intentionFormat(record) }}
            </span>
            <span slot="sex" slot-scope="text, record">
              {{ sexFormat(record) }}
            </span>
            <span slot="operation" slot-scope="text, record">
              <a-divider type="vertical" v-hasPermi="['manager:student:edit']" />
              <a @click="$refs.createForm.handleUpdate(record, undefined,queryParam.deptId,false);getList()" v-hasPermi="['manager:student:edit']">
                修改
              </a>
              <a-divider type="vertical" v-hasPermi="['manager:student:remove']" />
              <a @click="$refs.createForm.handleUpdate(record, undefined,queryParam.deptId,true)" v-if="record.status == 'A'">
                报名
              </a>
            </span>
          </a-table>
          <!-- 分页 -->
          <a-pagination
            class="ant-table-pagination"
            show-size-changer
            show-quick-jumper
            :current="queryParam.pageNum"
            :total="total"
            :page-size="queryParam.pageSize"
            :showTotal="total => `共 ${total} 条`"
            @showSizeChange="onShowSizeChange"
            @change="changeSize"
          />
        </a-col>
      </a-row>
    </a-card>
    <a-modal v-model="openProxy" title="商机代理人" @ok="addOrUpdateProxy">
      <a-form >
        <a-form-model-item label="上课校区" prop="deptId" >
            <a-tree-select
              v-model="proxyForm.deptId"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="deptOptions"
              placeholder="请选择上课校区"
              :replaceFields="{children:'children', title:'label', key:'id', value: 'id' }	"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item label="代理人" prop="userId" >
            <a-select placeholder="请选择商机归属人" v-model="proxyForm.userId">
              <a-select-option v-for="(d, index) in dataSource" :key="index" :value="d.id" >{{ d.name }}</a-select-option>
            </a-select>
            <!-- <a-auto-complete 
              placeholder="请选择代理人"
              v-model="value"
              :value="value"
              class="certain-category-search" 
              dropdown-class-name="certain-category-search-dropdown"
              :dropdown-match-select-width="false"
              :dropdown-style="{ width: '300px' }"
              size="small"
              style="width: 100%"
              @select="changeValue"
              option-label-prop="value">
              <template slot="dataSource">
                <a-select-opt-group v-for="group in dataSource" :key="group.title">
                  <span slot="label">{{ group.title }}</span>
                  <a-select-option v-for="opt in group.children" :key="opt.id" :value="opt.title">
                    {{ opt.title }}
                  </a-select-option>
                </a-select-opt-group>
              </template>
            </a-auto-complete> -->
          </a-form-model-item>
      </a-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { listStudent, delStudent,getOwnerGroup,getProxyInfo,addProxy} from '@/api/manager/student'
import CreateForm from './modules/CreateForm'
import { tableMixin } from '@/store/table-mixin'
import storage from'store'
import DeptTree from '../../system/user/modules/DeptTree'
import { treeselect } from '@/api/system/dept'

export default {
  name: 'Student',
  components: {
    CreateForm,
    DeptTree
  },
  mixins: [tableMixin],
  data () {
    return {
      dataSource:[],
      value:null,
      proxyForm:{
        userId:null,
        deptId:null,
        studentId:null,
        ids:[]
      },
      openProxy:false,
      // 部门树选项
      deptOptions: [{
        id: 0,
        label: '',
        children: []
      }],
      gutter:24,
      deptFlag: false,
      list: [],
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      loading: false,
      total: 0,
      //班型
      classTypeOptions:[],
      // 商机来源字典
      sourceOptions: [],
      // 商机意向字典
      intentionOptions: [],
      // 性别字典
      sexOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParam: {
        deptId:0,
        name: null,
        avater: null,
        cardNo: null,
        birthday: null,
        curator: null,
        phone: null,
        source: null,
        ascription: null,
        ascriptionSale: null,
        intention: null,
        product: null,
        age: null,
        sex: null,
        height: null,
        weight: null,
        school: null,
        address: null,
        proxyId: null,
        nature: null,
        status: null,
        deptId: null,
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'create_time',
        isAsc: 'desc',
      },
      columns: [
        {
          title: '学员名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
          ellipsis: false,
          align: 'center'
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '商机归属校区',
          dataIndex: 'deptName',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '归属人',
          dataIndex: 'ascriptionSaleName',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '代理人',
          dataIndex: 'proxyName',
          ellipsis: true,
          align: 'center'
        },{
          title: '试课教练',
          dataIndex: 'ascriptionTeacherName',
          ellipsis: true,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'dictName',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '商机来源',
          dataIndex: 'source',
          scopedSlots: { customRender: 'source' },
          ellipsis: false,
          align: 'center'
        },{
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: false,
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          align: 'center'
        }
      ]
    }
  },
  filters: {
  },
  created () {
    this.getOwner();
    this.deptInit();
    this.getTreeselect()
    this.getList()
    this.getDicts('business_source').then(response => {
      this.sourceOptions = response.data
    })
    this.getDicts('business_opportunity').then(response => {
      this.intentionOptions = response.data
    })
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getDicts('business_opportunity').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('class_type').then(response => {
      this.classTypeOptions = response.data
    })
  },
  computed: {
  },
  watch: {
  },
  methods: {
    hanleFilter(input, option){
      return (
        option.componentOptions.children[0].text.indexOf(input) >= 0
      );
    },
    getOwner(){
      getOwnerGroup().then(resp => {
        this.dataSource = resp.data;
      });
    },
    changeValue(value,option){
      this.proxyForm.userId = option.data.key
    },
    openProxyModel(){
      getProxyInfo(this.ids).then(resp => {
        this.proxyForm = {};
        if(resp.data){
          this.proxyForm = resp.data;
          this.value = resp.data.userName;
        }
        this.proxyForm.ids = this.ids;
        this.openProxy = true;

      });
    },
    deptInit(){
      this.deptFlag = storage.get("deptId") == 100;
      this.queryParam.deptId = storage.get("deptId")
      
      if(this.deptFlag){
        this.gutter = 20;
      }else{
        this.gutter = 24;
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect () {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    clickDeptNode (deptId) {
      this.queryParam.deptId = deptId
      this.handleQuery()
    },
    /** 查询学员信息列表 */
    getList () {
      this.loading = true
      listStudent(this.queryParam).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 商机来源字典翻译
    sourceFormat (row, column) {
      return this.selectDictLabel(this.sourceOptions, row.source)
    },
    // 商机意向字典翻译
    intentionFormat (row, column) {
      return this.selectDictLabel(this.intentionOptions, row.intention)
    },
    // 性别字典翻译
    sexFormat (row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex)
    },
    // 状态字典翻译
    statusFormat (row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParam = {
        name: undefined,
        avater: undefined,
        cardNo: undefined,
        birthday: undefined,
        curator: undefined,
        phone: undefined,
        source: undefined,
        ascription: undefined,
        ascriptionSale: undefined,
        intention: undefined,
        product: undefined,
        age: undefined,
        sex: undefined,
        height: undefined,
        weight: undefined,
        school: undefined,
        address: undefined,
        proxyId: undefined,
        nature: undefined,
        status: undefined,
        deptId: undefined,
        pageNum: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    onShowSizeChange (current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize (current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    addOrUpdateProxy(){
      if(this.proxyForm.userId == null){
        this.$message.error('请选择商机代理人！')
        return;
      }if(this.proxyForm.deptId == null){
        this.$message.error('请选择校区！')
        return;
      }
      addProxy(this.proxyForm).then(resp => {
        if(resp.code == '200'){
          this.$message.success(
            '商机代理人设置成功！',
            3
          )
          this.getList()
          this.openProxy = false;
        }else{
          this.$message.error(resp.msg);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      var that = this
      const ids = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中编号为' + ids + '的数据',
        onOk () {
          return delStudent(ids)
            .then(() => {
              that.onSelectChange([], [])
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          that.download('manager/student/export', {
            ...that.queryParam
          }, `student_${new Date().getTime()}.xlsx`)
        },
        onCancel () {}
      })
    }
  }
}
</script>
